package com.desksoft.ecommerce.util.html.element.variable;

import java.util.HashMap;
import java.util.Map;

import com.desksoft.ecommerce.util.html.element.variable.calculate.DateCalculateBean;
import com.desksoft.ecommerce.util.html.element.variable.calculate.ICalculateBean;

/**
 * 可运算的变量
 * $Calculate{ @p1, @p2, @p3...}
 * @p1  第一个参数代表是哪种类型的运算
 * @p2  第二个参数开始往后代表各种运算的参数
 * @author Administrator
 *
 */
public class CalculateVariable extends Variable {

	
	protected static Map<String, ICalculateBean> calculateBeanMap = new HashMap<String, ICalculateBean>();
	
	protected static void put(ICalculateBean calculateBean){
		calculateBeanMap.put(calculateBean.getToken(), calculateBean);
	}
	
	static {
		put(new DateCalculateBean());
	}
	
	@Override
	public String getType() {
		return "Calculate";
	}

	@Override
	public void initVariable() {
		
	}

	@Override
	protected String getLocalValue(String paramsString) {
		String[] params = getParams(paramsString);
		
		ICalculateBean bean = getCalculateBean(params[0]);
		
		return bean.getVariable(params);
	}

	/**
	 * 取得所有运算参数
	 */
	public String[] getParams(String paramsString){
		if (paramsString == null){
			throw new RuntimeException("动态变量$Calculate{@p1, @p2, @p3...}中参数部分不能为空.");
		}
		return paramsString.split(",");
	}
	
	/**
	 * 取得运算Bean
	 */
	public ICalculateBean getCalculateBean(String key){
		
		if (key == null){
			throw new RuntimeException("取运算Bean时，key不能为null.");
		}
		
		ICalculateBean bean = calculateBeanMap.get(key);
		if (bean == null){
			throw new RuntimeException("没有找到类型为 " + key + " 的运算Bean实例");
		}
		
		return bean;
	}
	
	
}
